<template>
  <div>
    <form action="/">
      <van-search
        v-model.trim="keywords"
        show-action
        class="search-inp"
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShowResult = false"
      />
    </form>
    <component
      @Update-keywords="onSearch"
      :keywrods="keywords"
      :is="componentName"
    />
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchResult from './components/SearchResult.vue'
import SearchSuggestions from './components/SearchSuggestions.vue'

import { mapMutations, mapState } from 'vuex'
import { set } from 'vue'
export default {
  computed: {
    ...mapState(['historys']),
    componentName() {
      // 搜索框没有实际内容的时候 渲染 搜索历史
      if (this.keywords === '') {
        // keywords 一定有值
        return SearchHistory
      }
      // 要么渲染搜索建议   要么渲染搜索结果
      if (this.isShowResult) {
        return SearchResult
      }
      //渲染搜索建议
      return SearchSuggestions
    }
  },
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestions
  },
  data() {
    return {
      keywords: '',
      isShowResult: false // 记录了是否触发了搜索事件
    }
  },

  methods: {
    ...mapMutations(['SET_HISTORY']),
    onSearch(val) {
      this.keywords = val

      let newHistorys = [this.keywords, ...this.historys]
      // 去重  new Set()
      newHistorys = [...new Set(newHistorys)]
      this.SET_HISTORY(newHistorys)
      this.isShowResult = true
    },
    onCancel() {
      // this.$toast('取消')
      // 触发取消 先清空keywords 再触发onCancel
      if (this.keywords === '') {
        this.$router.go(-1)
        // 返回上一层
      } else {
        this.keywords = ''
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-inp {
  .van-search__action {
    color: #fff;
  }
}
</style>
